package com.taptech.doufu.weex.http;

import android.content.Context;
import android.text.TextUtils;

import com.taptech.doufu.util.HttpRequestUtil;
import com.taptech.doufu.app.WeMediaApplication;
import com.taptech.doufu.constant.Constant;
import com.taptech.doufu.services.personalcenter.AccountService;
import com.taptech.doufu.util.DateUtil;
import com.taptech.doufu.util.PackageUtils;
import com.taptech.doufu.net.httputils.DiaobaoCookieStore;

import org.apache.http.client.protocol.ClientContext;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.json.JSONObject;

import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * Created by qlx on 2016/12/10.
 */

public class TFCookieUtil {
    private static final String COOKIE = "cookie";
    private static String lastUid = null;
    private static DiaobaoCookieStore cookies = null;

    private static BasicClientCookie xxCookie;


    /*
     * 获得cookies
     */

    public static DiaobaoCookieStore  getCookies(){
        try {
            if (isNeedUpdateCookies()){
                cookies = null;
            }
            createCookiesIfNeed();
            updateXXCookieIfNeed();
        }catch (Exception e){
            e.printStackTrace();
        }

        return cookies;
    }
    /*
     * 将coockies 转换为字符串
     */
    public static String cookieHeader(DiaobaoCookieStore cookieStore) {
        List<Cookie> cookies = cookieStore.getCookies();
        StringBuilder cookieHeader = new StringBuilder();
        for (int i = 0, size = cookies.size(); i < size; i++) {
            if (i > 0) {
                cookieHeader.append("; ");
            }
            Cookie cookie = cookies.get(i);
            cookieHeader.append(cookie.getName()).append('=').append(cookie.getValue());
        }
        return cookieHeader.toString();
    }

    /*
     * 获得cookies
     * @param xx 性向 根据xx来生成对应的cookies
     */
    public static DiaobaoCookieStore  getCookies(String xx){
        if (isNeedUpdateCookies()){
            cookies = null;
        }
        createCookiesIfNeed();
        setXXCookie(xx);



        return cookies;
    }

   /*
    * 获得cookies
    * @param extraCoockie 添加额外的coockie
    */
    public static DiaobaoCookieStore  getCookies(HashMap<String,String> extraCoockie){
        if (isNeedUpdateCookies()){
            cookies = null;
        }
        createCookiesIfNeed();
        updateXXCookieIfNeed();
        for (Map.Entry<String, String> entry : extraCoockie.entrySet()) {
            if (entry.getKey() == "xx"){
                setXXCookie(entry.getValue());
            }else {
                BasicClientCookie cookie = new BasicClientCookie(entry.getKey(), (String) entry.getValue());
                cookies.addCookie(cookie);
            }
        }
        DiaobaoCookieStore res = cookies;
        setNeedUpdate();
        return res;
    }




    // 设置后coockies会重新生成
    public static void setNeedUpdate(){
        cookies = null;
    }

    // private

    private static boolean isNeedUpdateCookies(){
        String uid = null;
        if (AccountService.getInstance().isLogin() == true){
            uid = AccountService.getInstance().getUserUid();
        }
        return  uid != lastUid;
    }

    private static BasicClientCookie getXxCookie(){
        if (xxCookie == null){
            xxCookie = new BasicClientCookie("xx" , ((WeMediaApplication)(WeMediaApplication.applicationContext)).sexType);
            xxCookie.setDomain("doufu.la");
            xxCookie.setPath("/");
            xxCookie.setExpiryDate(DateUtil.strToDate("2034-12-31"));
        }
        return xxCookie;
    }

    private static void updateXXCookieIfNeed(){
        BasicClientCookie cookie = getXxCookie();
        if (cookie.getValue() != ((WeMediaApplication)(WeMediaApplication.applicationContext)).sexType){
            cookie.setValue(((WeMediaApplication)(WeMediaApplication.applicationContext)).sexType);
        }
    }

    private static void setXXCookie(String xx){
        BasicClientCookie cookie = getXxCookie();
        if (cookie.getValue() != xx){
            cookie.setValue(xx);
        }
    }


    private static void  createCookiesIfNeed(){
        if (cookies == null){
            cookies = new DiaobaoCookieStore();
            if (AccountService.getInstance().isLogin()){
                try
                {
                    String json = WeMediaApplication.applicationContext.getSharedPreferences(COOKIE, Context.MODE_PRIVATE).getString(AccountService.getInstance().getUserUid(), null);
                    JSONObject obj = new JSONObject(json);
                    DiaobaoCookieStore store = new DiaobaoCookieStore();
                    Iterator<String> it = obj.keys();
                    while (it.hasNext()) {
                        String key =  it.next();
                        if (!key.equals(Constant.DOMAIN) && !key.equals(Constant.DATE)) {
                            if (key.equals(DiaobaoCookieStore.AV)){
                                BasicClientCookie cookie = new BasicClientCookie(key, PackageUtils.versionName);
                                Date date = DateUtil.strToDate(obj.getString(Constant.DATE));
                                cookie.setExpiryDate(date);
                                String domain = (String) obj.get(Constant.DOMAIN);
                                if (!TextUtils.isEmpty(domain)) {
                                    if (domain.equals("diaobao.la")){
                                        domain = "doufu.la";
                                    }
                                    cookie.setDomain(domain);
                                }
                                store.addCookie(cookie);
                            }else{
                                BasicClientCookie cookie = new BasicClientCookie(key, (String) obj.get(key));
                                Date date = DateUtil.strToDate(obj.getString(Constant.DATE));
                                cookie.setExpiryDate(date);
                                String domain = (String) obj.get(Constant.DOMAIN);
                                if (!TextUtils.isEmpty(domain)) {
                                    if (domain.equals("diaobao.la")){
                                        domain = "doufu.la";
                                    }
                                    cookie.setDomain(domain);
                                }
                                store.addCookie(cookie);
                            }
                        }
                    }
                    cookies = store;
                } catch (Exception e)
                {
                    e.printStackTrace();
                }
            }
            cookies.addCookie(getXxCookie());
            HttpRequestUtil.getContext().setAttribute(ClientContext.COOKIE_STORE, cookies);
            if (AccountService.getInstance().isLogin()){
                lastUid = AccountService.getInstance().getUserUid();
            }else {
                lastUid = null;
            }
        }
    }



}
